﻿using System.Data.Linq;
using System.Linq;
using JetBrains.Annotations;

namespace StreetPacMan.Server
{
    public interface IApplesStorage
    {
        Apple[] GetAllApplesForPlayer(int playerId);
    }

    [UsedByIoc]
    public class ApplesStorage : IApplesStorage
    {
        private readonly IConnectionProvider _ConnectionProvider;

        public ApplesStorage(IConnectionProvider connectionProvider, IGameRules gameRules)
        {
            _ConnectionProvider = connectionProvider;
        }

        public Apple[] GetAllApplesForPlayer(int playerId)
        {
            using (var dbConnection = _ConnectionProvider.GetConnection())
            using (var pacManDataContext = new PacManDataContext(dbConnection))
            {
                var dataLoadOptions = new DataLoadOptions();
                dataLoadOptions.LoadWith<Player>(x => x.Game);
                pacManDataContext.LoadOptions = dataLoadOptions;

                var requestingUser = pacManDataContext.Players.Where(x => x.Id == playerId).Single();
                if (requestingUser.RoleEnum==PlayerRole.Ghost)
                {
                    return new Apple[0];
                }

                return pacManDataContext
                    .Apples
                    .Where(x => x.GameId == requestingUser.GameId)
                    .Where(x => x.State == (int) AppleState.Active)
                    .ToArray();
            }
        }
    }
}